<template>
  <div>
    <a-modal
      :visible.sync="visible"
      v-bind="$attrs"
      v-on="$listeners"
      :maskClosable="false"
      :footer="null"
      width="846px"
      title="资料上传"
      wrapClassName="add-modal-container"
      @cancel="closeModal()"
    >
      <div class="curve-modal-body">
        <a-form-model ref="ruleForm" :model="form" :rules="rules">
          <a-row :gutter="0">
            <a-col :span="8">
              <a-form-model-item label="总分">
                <a-input v-model="baseInfo.singleScore" disabled />
              </a-form-model-item>
              <span class="unit">分</span>
            </a-col>
          </a-row>
          <a-row :gutter="0">
            <a-col :span="24">
              <a-form-model-item label="五级指标">
                <a-input
                  v-model="baseInfo.assessmentContent"
                  disabled
                  type="textarea"
                  style="height: 80px"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="0">
            <a-col :span="24">
              <a-form-model-item
                label="上传资料"
                prop="file"
                :rules="{
                  required: true,
                  message: '请选择资料',
                }"
              >
                <bjUploadFile
                  :count="6"
                  v-model="form.file"
                  @change="upLoadFile($event)"
                  @download="downloadFile($event)"
                  @preview="viewFile($event)"
                  :replaceFields="{
                    fileName: 'fileName',
                    fileSize: 'fileSize',
                    fileType: 'fileType',
                    fileUrl: 'fileUrl',
                  }"
                ></bjUploadFile>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="0">
            <a-col :span="24">
              <a-form-model-item label="自评分" prop="ownScore">
                <a-input-number
                  style="width: 100%"
                  placeholder="请输入自评分"
                  v-model="form.ownScore"
                  :min="isMinScore"
                  :max="isMaxScore"
                />
              </a-form-model-item>
              <span class="unit">分</span>
            </a-col>
          </a-row>
          <a-row :gutter="0">
            <a-col :span="24">
              <a-form-model-item label="备注">
                <a-input
                  type="textarea"
                  placeholder="请输入备注"
                  :rows="4"
                  v-model="form.ownRemark"
                  :maxLength="255"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <div class="curve-modal-footer">
        <a-button type="default" @click="closeModal()">取消 </a-button>
        <a-button type="primary" @click="onSubmit()" :loading="buttonLoading">
          确定
        </a-button>
      </div>
    </a-modal>
    <!-- 附件预览弹窗 -->
    <previewModal
      :visible.sync="previewVisible"
      :loading="previewLoading"
      ref="previewModal"
    ></previewModal>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getToken } from "@/utils/TopVUI";
import { axios } from "@/utils/request";
import UploadFile from "@/components/TopVUI/k-form-design/packages/UploadFile";
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
import { downloadDfs } from "@/utils/TopVUI";
import previewModal from "@/pages/document/minio/previewModal";
export default {
  name: "materialUploadModal",
  components: {
    bjUploadFile,
    previewModal,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: "",
    },
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
    isMinScore() {
      if (this.baseInfo.singleScore < 0) {
        return this.baseInfo.singleScore;
      } else {
        return 0;
      }
    },
    isMaxScore() {
      if (this.baseInfo.singleScore > 0) {
        return this.baseInfo.singleScore;
      } else {
        return 0;
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      resultData: {},
      baseInfo: {},
      form: {
        //附件
        file: [],
        //自评分
        ownScore: "",
        //备注
        ownRemark: "",
      },
      rules: {
        ownScore: [
          { required: true, message: "请输入自评分", trigger: "blur" },
        ],
      },
      buttonLoading: false,
      upLoadFileData: {
        //上传文件数据
        options: {
          width: "100%", //宽度
          drag: false, //是否可拖拽
          fileName: "uploadFiles", //文件参数名
          multiple: true, //是否支持多选
          limit: 10, //上传最大数量
          disabled: false, //是否禁用
          data: "{}", //额外参数（json格式）
          action: "/probusiness/qeTaskDeal/uploadFiles", //上传请求地址
          headers: {}, //请求头部
          downloadWay: "a", //下载方式  可选a、ajax
          dynamicFun: "", //动态函数名
          placeholder: "上传", //上传区文字提示
          defaultValue: [], //默认值
        },
      },
      upLoadFileConfigData: {}, //上传文件数据
      previewVisible: false,
      previewLoading: false,
    };
  },
  methods: {
    //下载附件
    downloadFile(file) {
      let { url } = file;
      if (!url) {
        this.$message.success("文件不存在", 1.5);
        return;
      }
      downloadDfs(url);
    },
    // 预览附件
    viewFile(file) {
      this.previewLoading = true;
      let { url } = file;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewVisible = true;
      this.previewLoading = false;
    },
    //上传附件
    upLoadFile({ file, index }) {
      let formData = new FormData();
      formData.append("uploadFiles", file);
      this.$set(this.form["file"][index], "loading", true);
      axios
        .post(`/probusiness/qeTaskDeal/uploadFiles`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          let { successFileId = [] } = res.data;
          this.$set(
            this.form.file[this.form.file.length - 1],
            "uuid",
            successFileId.toString()
          );
        })
        .catch((_) => {
          this.$set(this.form["file"][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form["file"][index], "loading", false);
        });
    },
    getData() {
      Promise.all([this.getDetail(), this.getTable()])
        .then()
        .finally((_) => {});
    },

    //查询详情
    getDetail() {
      return new Promise((resolve, reject) => {
        axios
          .get(
            `/probusiness/qeTaskDeal/getConfigDetailData?id=${this.id}`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.resultData = res?.data || {};
            this.baseInfo = res.data?.qeEvaluationContent || {};
            this.form.ownRemark = this.resultData.ownRemark;
            this.form.ownScore =
              this.resultData.ownScore || this.baseInfo.singleScore;
            resolve();
          })
          .catch((_) => {
            this.resultData = {};
            this.baseInfo = {};
            this.form.ownRemark = "";
            this.form.ownScore = "";
            reject();
          });
      });
    },
    //查询表格
    getTable() {
      return new Promise((resolve, reject) => {
        axios
          .get(
            `/probusiness/qeTaskDeal/getFileRecord?id=${this.id}`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.form.file = res.data || [];
            resolve();
          })
          .catch((_) => {
            this.form.file = [];
            reject();
          });
      });
    },

    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          let { file = [], ownScore, ownRemark } = this.form;
          let ids = file.map((item) => item.uuid);
          let formJson = {
            ownScore,
            ownRemark,
            fileIds: ids,
          };
          axios
            .post(
              `/probusiness/qeTaskDeal/saveOrUpdateFileData?id=${this.id}`,
              formJson,
              {
                headers: {
                  "Content-Type": "application/json",
                },
              }
            )
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("操作成功", 1.5);
                this.$parent.$parent.getStatistics();
                this.$parent.$parent.getTableData();
                this.closeModal();
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch((_) => {})
            .finally((_) => {
              this.buttonLoading = false;
            });
        }
      });
    },
    //关闭弹窗
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
    //重置表单
    resetForm() {
      this.form = {
        //附件
        file: [],
        //自评分
        ownScore: "",
        //备注
        ownRemark: "",
      };
      this.$refs.ruleForm.resetFields();
    },
  },
};
</script>

<style lang="less" scoped>
@primary-color: @primary-color;
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
  }
  .ant-modal-header {
    position: relative;
    .ant-modal-title {
      &::before {
        content: "";
        position: absolute;
        top: 18px;
        left: 10px;
        background-color: @primary-color;
        height: 17px;
        width: 5px;
      }
    }
  }

  .curve-modal-body {
    padding: 14px;
    padding-right: 60px;
    max-height: 700px;
    overflow: auto;
  }
  .curve-modal-footer {
    padding: 10px 16px;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #e8e8e8;
    border-radius: 0 0 4px 4px;
    button {
      &:last-child {
        margin-left: 20px;
      }
    }
  }
  .unit {
    position: absolute;
    top: 12px;
    right: -22px;
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #333333;
  }
  .ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 120px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
    }
  }
  .bj-upload-file {
    .choosed-file-warp {
      width: 652px;
    }
  }
}
</style>
